package com.miao.teacher.models;

import java.io.File;
import java.io.IOException;

import android.media.MediaRecorder;

public class Recorder {
	MediaRecorder mediaRecorder;
	private boolean isRecording;
	private boolean isReady;
	private File file;

	public static Recorder create(File f) {
		Recorder re = new Recorder(f);
		if (re.isReady())
			return re;
		return null;
	}

	private Recorder(File f) {
		isRecording = false;
		isReady = false;
		file = f;
		mediaRecorder = new MediaRecorder();
		mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
		mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		mediaRecorder.setAudioEncodingBitRate(16000);
		mediaRecorder.setOutputFile(file.toString());
		try {
			mediaRecorder.prepare();
			mediaRecorder.start();
			isReady = true;
		} catch (IllegalStateException e) {
			isReady = false;
			e.printStackTrace();
		} catch (IOException e) {
			isReady = false;
			e.printStackTrace();
		}
	}

	public File getFile() {
		return file;
	}

	public boolean isReady() {
		return isReady;
	}

	@SuppressWarnings("unused")
	public boolean isRecording() {
		return isRecording;
	}

	public void start() {
		try {
			//mediaRecorder.start();
			isRecording = true;
		} catch (Exception er) {
		}
	}

	public void stop() {
		try {
			mediaRecorder.stop();
			isRecording = false;
		} catch (Exception er) {
		}
	}

	public void release() {
		try {
			mediaRecorder.release();
			mediaRecorder = null;
		} catch (Exception er) {
		}
	}
}
